package com.zhisheng.products.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhisheng.exception.MyBusinessException;
import com.zhisheng.products.mapper.ProductsMapper;
import com.zhisheng.products.entity.Products;
import com.zhisheng.products.service.ProductsService;
import com.zhisheng.result.MyResponseResult;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * (Products)表服务实现类
 *
 * @author 全哥
 * @since 2025-02-22 15:21:07
 */
@Service("productsService")
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products> implements ProductsService {

    @Override
    public MyResponseResult<String> kouJian(Map<Integer, Integer> goods) {
        /*
            按照map集合的key,扣减value数量的商品,如果扣减成功,则继续,如果扣减失败,则抛出异常即可
         */
        for (Integer key : goods.keySet()) {
            Products products = this.getById(key);
            if (products.getStock() < goods.get(key)) {
                throw new MyBusinessException(key+"号商品库存不足!还剩:"+ products.getStock()+",要买:"+goods.get(key));
            }
            products.setStock(products.getStock()- goods.get(key));
            updateById(products);
        }
        return MyResponseResult.success("扣减成功!");
    }
}

